package com.ev.common.jobs;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.ev.asl.constant.AslConstant;
import com.ev.asl.dao.CheckResultDao;
import com.ev.asl.dao.CheckResultDetailDao;
import com.ev.asl.domain.CheckResultDO;
import com.ev.asl.domain.CheckResultDetailDO;
import com.ev.asl.service.KisBasicsService;
import com.ev.asl.vo.voBillOfPull.KisReceiveStockVo;
import com.ev.custom.domain.MaterielDO;
import com.ev.custom.service.MaterielService;
import com.ev.custom.service.NoticeService;
import com.ev.framework.config.Constant;
import com.ev.framework.config.ConstantForMES;
import com.ev.framework.exception.BDException;
import com.ev.framework.utils.DateFormatUtil;
import com.ev.k3cloudBusiness.dto.ErpInOrOutStockParam;
import com.ev.k3cloudBusiness.service.impl.SyncPushBillAdapter;
import com.ev.k3cloudBusiness.vo.KisApiResultVOS;
import com.ev.system.service.UserService;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.Triple;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class ExpiredInventoryJob {
    @Autowired
    private KisBasicsService kisBasicsService;

    @Autowired
    private SyncPushBillAdapter syncPushBillAdapter;

    @Autowired
    private CheckResultDao dao;

    @Autowired
    private CheckResultDetailDao detailDao;

    @Autowired
    private MaterielService materielService;

    @Autowired
    private UserService userService;

    @Autowired
    NoticeService noticeService;

//    @Scheduled(cron = "0 0 1 * * ?") //凌晨1点开始查询过期库存/超过60天过期
//    @Scheduled(cron = "0 0 0/1  * * ?") //凌晨1点开始查询过期库存/超过60天过期
    @Scheduled(cron = "0 0/5 * * * ?") //凌晨1点开始查询过期库存/超过60天过期
    private void executeInternal() {
        try {
            //查询过期库存
            queryExpiredInventory();
//            test();
        } catch (Exception e) {
            log.error("==========================查询异常======================================",e);
            log.error(e.getMessage());
        }
    }
    private void test() {
        Map<String, Object> detail = materielService.getDetail(503L);
        System.out.println(detail.toString());
    }

    private void queryExpiredInventory() {
        log.info("==========================查询库存======================================");
        String filter = "and 仓库名称='原料仓库' and 物料代码 != '40.07.001' and 物料代码 != '40.07.002'";
        Triple<Boolean, String, List<KisReceiveStockVo>> stockList = kisBasicsService.realTimeStockBalanceEnquiry222(filter);
        if (!stockList.getLeft()) {
            String msg = stockList.getMiddle();
            log.error("==========================查询-异常======================================");
            throw new BDException(msg);
        }
        List<KisReceiveStockVo> stockVos = stockList.getRight();
        log.info("==========================stockVos======================================");
        log.info(JSON.toJSONString(stockVos));
        List<KisReceiveStockVo> stockVoList = stockList.getRight();
        for (KisReceiveStockVo kisReceiveStockVo : stockVoList) {
            DateTime dateTime = null;
            try {
                dateTime = DateUtil.parse(kisReceiveStockVo.getFBatchNo(), "yyMMdd");
            }catch (Exception e) {
                log.info("==========================日期格式不正确,跳过======================================");
                continue;
            }
            if(DateUtil.offsetMonth(dateTime,12).isBefore(new Date())){
                log.info("==========================过期库存,开始调拨======================================");
                ErpInOrOutStockParam param = new ErpInOrOutStockParam();
                List<ErpInOrOutStockParam> params = new ArrayList<>();
                param.setMaterialId(Integer.parseInt(kisReceiveStockVo.getFItemID()));
                param.setQty(new BigDecimal(kisReceiveStockVo.getFQty()));
                param.setBatch(kisReceiveStockVo.getFBatchNo());
                param.setWarehouseId(Integer.parseInt(kisReceiveStockVo.getFStockID()));
                param.setWarehItemId(Integer.parseInt(kisReceiveStockVo.getFStockPlaceID()));
                param.setMoveInWarehouseId(Constant.warehouse10.intValue());
                params.add(param);
                KisApiResultVOS vos = syncPushBillAdapter.inventoryTransfer(params);
                JSONArray jsonArray = new JSONArray(vos.getMsg());
                JSONObject jsonObject = jsonArray.getJSONObject(0);
                Object billNo = jsonObject.get("BillNo");
                System.out.println(JSON.toJSONString(vos));
                log.info("==========================库存挑拨完成，生成过期检验======================================");
                if(vos.getStatus() == 0){
                    CheckResultDO checkResultDO = new CheckResultDO();
                    checkResultDO.setType(AslConstant.TWO);
                    checkResultDO.setBillDate(new Date());
                    checkResultDO.setCheckNo(AslConstant.TWO + DateUtil.formatDate(new Date()));
                    checkResultDO.setInstructionNo(billNo == null ? null : billNo.toString());
                    String prefix = DateFormatUtil.getWorkOrderno(ConstantForMES.CHECK_PLAN_JCCJ, new Date());
                    Map<String, Object> paramss = Maps.newHashMapWithExpectedSize(3);
                    paramss.put("checkNo", prefix);
                    paramss.put("offset", 0);
                    paramss.put("limit", 1);
                    List<CheckResultDO> checkResultDOList = dao.list(paramss);
                    String suffix = null;
                    if (!checkResultDOList.isEmpty()) {
                        suffix = checkResultDOList.get(0).getCheckNo();
                    }
                    checkResultDO.setCheckNo(DateFormatUtil.getWorkOrderno(prefix, suffix));
                    checkResultDO.setStatus(AslConstant.NO);
                    checkResultDO.setDelFlag(AslConstant.NO);
                    //产品id和产品名称
                    checkResultDO.setProductId(Long.parseLong(kisReceiveStockVo.getFItemID()));
                    checkResultDO.setProduct(kisReceiveStockVo.getFItemName());
                    checkResultDO.setMaterielId(Long.parseLong(kisReceiveStockVo.getFItemID()));
                    checkResultDO.setMaterielName(kisReceiveStockVo.getFItemName());
                    checkResultDO.setBatchNo(kisReceiveStockVo.getFBatchNo());
                    checkResultDO.setQty(new BigDecimal(kisReceiveStockVo.getFQty()));
                    checkResultDO.setMainUnitName(kisReceiveStockVo.getUnitName());
                    checkResultDO.setCreateTime(new Date());
                    checkResultDO.setRemarks("过期原材料自动调拨生成");
                    int result = dao.save(checkResultDO);
                    List<Long> toUsers = userService.getUserIdsByDept(266);//质检部
                    //给品质部
                    noticeService.sendCheckMessage(checkResultDO.getId(), toUsers, "过期检验新增提醒", "/basic/expiredInspectionAdd?id=", checkResultDO.getMaterielName()+"物料已过期，请收到原料后完成原料检验单");
                    //给陈巧兰
                    toUsers.clear();
                    toUsers.add(273L);//陈巧兰
                    noticeService.sendCheckMessage(checkResultDO.getId(), toUsers, "过期检验新增提醒", "/basic/expiredInspectionAdd?id=", checkResultDO.getMaterielName()+"物料已过期，请将物料送检品质部");
                    Map<String, Object> detail = materielService.getDetail(Long.parseLong(kisReceiveStockVo.getFItemID()));
                    log.info("==========================物料信息======================================");
                    log.info("物料id："+Long.parseLong(kisReceiveStockVo.getFItemID()));
                    log.info("物料详情："+JSON.toJSONString(detail));
                    if (result > AslConstant.ZERO) {
                        String[] checkItems = new String[]{"外观检查","颜色","MI","密度"};
                        List<CheckResultDetailDO> checkResultDetailDOS = new ArrayList<>();
                        for (String checkItem : checkItems) {
                            CheckResultDetailDO detailDO = new CheckResultDetailDO();
                            detailDO.setMainId(checkResultDO.getId());
                            detailDO.setCheckItemId(0L);
                            detailDO.setCheckItem(checkItem);
                            if(checkItem.equals("外观检查")){
//                                detailDO.setStatusValue();
                                detailDO.setSample(detail.get("visualInspection").toString());
                                detailDO.setCheckWay("目检");
                                detailDO.setMode("抽检");
                            }else if(checkItem.equals("颜色")){
//                                detailDO.setStatusValue();
                                detailDO.setSample(detail.get("colour").toString());
                                detailDO.setCheckWay("目检");
                                detailDO.setMode("抽检");
                            }else if(checkItem.equals("MI")){
//                                detailDO.setStatusValue();
                                detailDO.setSample(detail.get("mi").toString());
                                detailDO.setCheckWay("熔体流动率测定仪");
                                detailDO.setMode("抽检");
                            }else if(checkItem.equals("密度")){
//                                detailDO.setStatusValue();
                                detailDO.setSample(detail.get("density").toString());
                                detailDO.setCheckWay("供应商提供");
                                detailDO.setMode("抽检");
                            }
                            checkResultDetailDOS.add(detailDO);
                        }
                        detailDao.batchSave(checkResultDetailDOS);
                    }
                }else {
                    log.info("==========================调拨失败,跳过======================================");
                    log.error(vos.getMsg());
                }
            }

        }
    }

}
